package com.y4oung.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;

import com.huaban.analysis.jieba.SegToken;
import com.y4oung.model.Business;
import com.y4oung.model.User;
import com.y4oung.service.IBusinessService;
import com.y4oung.service.impl.BusiServiceImpl;
import com.y4oung.util.ResponseJsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.JiebaSegmenter.SegMode;
import com.y4oung.model.SearchHistory;
import com.y4oung.model.Title;
import com.y4oung.service.ISearchService;

@RequestMapping("search")
@Controller
public class SearchController {
    @Resource
	private ISearchService searchService;
	@Resource
    private IBusinessService businessService;
	
	@RequestMapping("keywordData.do")
	@ResponseBody
	public JSONObject getData(HttpServletRequest request, HttpServletResponse response){
		JSONObject json = new JSONObject();
		List<Title> tlist = new ArrayList<Title>();
		
		tlist.add(new Title("武汉"));

		json.put("data", tlist);
		return json;
	}
	
	@RequestMapping("/showSearch.do")
	//读取当前用户的搜索记录
	public void showSearch(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int userId = Integer.parseInt(request.getParameter("userId"));

        //通过userId获取数据库中用户搜索记录
        List<SearchHistory> searchHistoryList = this.searchService.showSearch(userId);   
        ObjectMapper mapper = new ObjectMapper();
        for (SearchHistory searchHistory : searchHistoryList) {
        	//关键字和时间
        	response.getWriter().write(mapper.writeValueAsString(sdf.format(searchHistory.getTime())+searchHistory.getKeyword()));
        }
        response.getWriter().close();
    }
	
	@RequestMapping("/insertSearch.do")
	//存储当前用户的搜索记录
	public void insertSearch(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = new Date();
        sdf.format(time);
        User u= (User)request.getSession().getAttribute("user");
        String keyword = request.getParameter("content");
        if(u!=null) {
            int userId = u.getId();
            JiebaSegmenter segmenter = new JiebaSegmenter();
            segmenter.process(keyword, SegMode.SEARCH);
            //存储用户id,当前时间,关键字
            this.searchService.insertSearch(userId, time, keyword);
        }
    }
	
	@RequestMapping("/deleteSearch.do")
	//删除当前用户的搜索记录
	public void deleteSearch(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        int userId = Integer.parseInt(request.getParameter("userId"));
        //根据userId删除数据库中相应数据
        this.searchService.deleteSearch(userId);
    }

    @RequestMapping(value = "/mainSearch.do",method = RequestMethod.POST)
    public String search(HttpServletRequest request, HttpServletResponse response){
	    String content = request.getParameter("content");
        Map<String, Object> map = new HashMap<String, Object>();
        //String columns = request.getParameter("columns");
        String keyword = "'"+content+"'";
        map.put("columns","name");
        map.put("keyword",keyword);
        List<Business> businessList = new ArrayList<Business>();
        List<Business> partlist = this.businessService.searchBusinessAccurate(map);
        if(partlist.size()!=0){
            businessList.addAll(partlist);
        }else{
            JiebaSegmenter segmenter = new JiebaSegmenter();
            List<SegToken> list= segmenter.process(content, SegMode.SEARCH);
            for (SegToken s:list ) {
                if(s.word.length()>1) { //避免分词分成单个字，这样就没有了查询的意义
                    keyword = "'%"+s.word+"%'";

                    map.put("columns", "name");
                    map.put("keyword", keyword);
                    partlist = this.businessService.searchBusiness(map);
                    //businessList.addAll(partlist);
                    for(Business ss : partlist){
                        if(!businessList.contains(ss)){
                            businessList.add(ss);
                        }
                    }
                }
            }
        }

        request.setAttribute("businessList",businessList);
        return "restaurantGallery";
	    //得到搜索结果
    }

    @RequestMapping("SearchSelect")
    public String searchBusiness(HttpServletRequest request, HttpServletResponse response) {
        String type = request.getParameter("type");
        String detail =request.getParameter("detail");
        return "restaurantGallery";
    }

}
